<?php
namespace Api\Controller;

use Api\Controller;

/**
 * 登录/注册业务
 * @package Api\Controller
 */
class IndexController extends AppController
{

    /**
     * 注册
     */
    public function register()
    {

        if (IS_POST) {
            $account = I('post.account');
            $password = I('post.password');
            $appid = I('post.appid');

            $username = I('post.username');
            $phone = I('post.phone');
            $gas_owner = I('post.gas_owner');
            $gas_name = I('post.gas_name');
            $gas_addr = I('post.gas_addr');
            /* 以#分割 格式:经度#纬度*/
            $gas_location = I('post.location');

        } elseif (IS_GET) {
            $account = I('get.account');
            $password = I('get.password');
            $appid = I('get.appid');

            $username = I('get.username');
            $phone = I('get.phone');
            $gas_owner = I('get.gas_owner');
            $gas_name = I('get.gas_name');
            $gas_addr = I('get.gas_addr');
            $gas_location = I('get.location');
        }

        if (empty($account) || empty($password)) {
            $this->apiReturn(422, '账号或密码不能为空', NULL, ApiReturn);
            return;
        }

        if ($this->isExist($account)) {
            $this->apiReturn(402, '此账号已注册', null, ApiReturn);
            return;
        }

        if (empty($username) || empty($gas_owner) || empty($gas_name)) {
            $this->apiReturn(422, '请求参数有误', NULL, ApiReturn);
            return;
        }

        if (empty($gas_location)) {
            $this->apiReturn(422, '油站位置参数有误', NULL, ApiReturn);
            return;
        }

        $currentTime = time();
        if (!empty($gas_location)) {
            $location = explode("#", $gas_location);
            $longitude = $location[0];
            $latitude = $location[1];
            $data_gas["addr_lon"] = $longitude;
            $data_gas["addr_lat"] = $latitude;
            $data_gas["owner_name"] = $gas_owner;
            $data_gas["name"] = $gas_name;
            $data_gas["addr"] = $gas_addr;
            $data_gas["create_at"] = $currentTime;
            $gas_result = D("gas_station")->add($data_gas);
        }

        if ($gas_result) {
            $data["gas_station_id"] = $gas_result;
        }

        $data["account"] = $account;

        $password = md5($account . $password);

        $data["password"] = $password;
        if (!empty($username)) {
            $data["user_name"] = $username;
        }

        if (!empty($phone)) {
            $data["phone_number"] = $phone;
        }

        $nonce = $this->createNoncestr(32);
        $tmpArr = array($nonce, $appid, $password, $account, $currentTime);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $token = md5($tmpStr);

        $data["user_token"] = $token;
        $data["expire_time"] = UserTokenExpireTime;
        $data["update_at"] = $currentTime;
        $data["create_at"] = $currentTime;

        $result = D('user')->add($data);

        if ($result) {
            $data = array(
                'account' => $account,
                'uid' => $result,
                'user_token' => $token,
                'expire_time' => UserTokenExpireTime,
                'registerTime' => $currentTime
            );
            $this->apiReturn(200, '注册成功', $data, ApiReturn);
        } else {
            $this->apiReturn(401, '注册失败', null, ApiReturn);
        }
    }

    /**
     *  登录
     */
    public function login()
    {
        if (IS_POST) {
            $account = I('post.account');
            $password = I('post.password');
            $appid = I('post.appid');

            $uid = I('post.uid');
            $user_token = I('post.user_token');
        } elseif (IS_GET) {
            $account = I('get.account');
            $password = I('get.password');
            $appid = I('get.appid');

            $uid = I('get.uid');
            $user_token = I('get.user_token');
        }

        if((empty($account) || empty($password))&& empty($user_token))
        {
            $this->apiReturn(422, '请重新登陆！', NULL, ApiReturn);

        }
        $this->writelog("1","login");
        $this->writelog("1",$account."|".$password."|".$user_token);
        //首先对token 信息进行处理
        if(!empty($user_token)){//如果token信息为空，则认为采用用户名+密码 形式登陆

            $result=$this->checktoken($user_token,$uid);
            if($result!='-1'){
                //通知用户更新
                $data = array(
                    'account' => $account,
                    'uid' => $uid,
                    'user_token' => $user_token,
                    'expire_time' => UserTokenExpireTime,
                    'registerTime' => time()
            );
                writelog("1","延期".$data);
                $this->apiReturn(200, '登录成功', $data, ApiReturn);
            }

        }





        if (empty($account) || empty($password)) {
            $this->apiReturn(422, '账号和密码不能为空', NULL, ApiReturn);
            return;
        }

        $password = md5($account . $password);

        /*检查是否存在此账户*/
        $condition['account'] = $account;
        $condition['password'] = $password;
        $resultFind = D('user')->where($condition)->find();
        if (!$resultFind) {
            $this->apiReturn(402, '账号或密码错误', null, ApiReturn);
            return;
        }

        /*如果存在则生成新的token*/
        $nonce = $this->createNoncestr(32);
        $currentTime = time();
        $tmpArr = array($nonce, $appid, $password, $account, $currentTime);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $token = md5($tmpStr);

        /*更新新的token*/
        $updataData['id'] = $resultFind['id'];
        $updataData['user_token'] = $token;
        $updataData['expire_time'] = UserTokenExpireTime;
        $updataData['update_at'] = $currentTime;
        $result = D('user')->save($updataData);

        /*通知客户端更新*/
        if ($result) {
            $data = array(
                'account' => $account,
                'uid' => $resultFind['id'],
                'user_token' => $token,
                'expire_time' => UserTokenExpireTime,
                'registerTime' => $currentTime
            );
            $this->apiReturn(200, '登录成功', $data, ApiReturn);
        } else {
            $this->apiReturn(401, '登录失败', null, ApiReturn);
        }
    }

    /**
     * 检测身份证是否异常
     */
    public function checkcard()
    {

        if (IS_POST) {
            $uid = I('post.uid');
            $user_token = I('post.user_token');
            $cardid = I('post.cardid');
        } elseif (IS_GET) {
            $uid = I('get.uid');
            $user_token = I('get.user_token');
            $cardid = I('get.cardid');
        }

        if (empty($uid) || empty($user_token) || empty($cardid)) {
            $this->apiReturn(422, '请求参数有误', NULL, ApiReturn);
            return;
        }

        $condition['id'] = $uid;
        $condition['user_token'] = $user_token;
        $resultFind = D('user')->where($condition)->find();
        if (!$resultFind) {
            $this->apiReturn(401, '此账户不存在或token有误', null, ApiReturn);
            return;
        }

        $current_at = time();
        $update_at = $resultFind["update_at"];

        if ($update_at - $current_at >= UserTokenExpireTime) {
            $this->apiReturn(402, '令牌已失效', null, ApiReturn);
            return;
        }
        //对token 进行续期
        $this->checktoken($user_token,$uid);

        $condition_find["sfzh"] = $cardid;

        $sps_find = D("suspicious")->where($condition_find)->select();

        if ($sps_find != null) {

            $sps_length = count($sps_find);

            $info["sfzh"] = $sps_find[$sps_length - 1]["sfzh"];
            $info["name"] = $sps_find[$sps_length - 1]["name"];
            $info["mz"] = $sps_find[$sps_length - 1]["mz"];
            $info["addr_now"] = $sps_find[$sps_length - 1]["resident_current"];
            $data["info"] = $info;

            $temp = "";
            for ($index = 0; $index < $sps_length; $index++) {
                $type[$index]["type"] = $sps_find[$index]["type"];
                if ($index < $sps_length - 1) {
                    $temp = $temp . $sps_find[$index]["type"] . "#";
                } else {
                    $temp = $temp . $sps_find[$index]["type"];
                }
            }
            $data["list_type"] = $type;
            $data_warn["cj_uid"] = $uid;
            $data_warn["cj_user_name"] = $resultFind["user_name"];
            $data_warn["susp_id"] = $sps_find[$sps_length - 1]["id"];
            $data_warn["susp_name"] = $sps_find[$sps_length - 1]["name"];
            $data_warn["susp_con"] = $temp;
            $data_warn["warn_at"] = time();
            D("warnings")->add($data_warn);

            $this->apiReturn(200, '查到可疑信息', $data, ApiReturn);
        } else {
            $this->apiReturn(200, '此人正常', null, ApiReturn);
        }

    }

    /**
     * 信息采集
     */
    public function submitcj()
    {
        if (IS_POST) {
            $uid = I('post.uid');
            $user_token = I('post.user_token');

            $cap = I('post.cap');
            $oil_num = I('post.oil_num');
            $aims_sfzh = I('post.aims_sfzh');
            $aims_name = I('post.aims_name');
            $aims_addr = I('post.aims_addr');
            $phone_number = I('post.aims_phone');
        } elseif (IS_GET) {
            $uid = I('get.uid');
            $user_token = I('get.user_token');

            $cap = I('get.cap');
            $oil_num = I('get.oil_num');
            $aims_sfzh = I('get.aims_sfzh');
            $aims_name = I('get.aims_name');
            $aims_addr = I('get.aims_addr');
            $phone_number = I('get.aims_phone');
        }
        if (empty($uid) || empty($user_token) || empty($aims_sfzh)) {
            $this->apiReturn(422, '请求参数有误', NULL, ApiReturn);
            return;
        }

        $condition['id'] = $uid;
        $condition['user_token'] = $user_token;
        $resultFind = D('user')->where($condition)->find();
        if (!$resultFind) {
            $this->apiReturn(401, '此账户不存在或token有误', null, ApiReturn);
            return;
        }

        $current_at = time();
        $update_at = $resultFind["update_at"];

        if ($update_at - $current_at >= UserTokenExpireTime) {
            $this->apiReturn(402, '令牌已失效', null, ApiReturn);
            return;
        }
        //对token 进行续期
        $this->checktoken($user_token,$uid);

        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 0;// 设置附件上传大小
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg','bmp');// 设置附件上传类型
        $upload->rootPath = FileRootPath; // 设置附件上传根目录
        $upload->savePath = ImagePath; // 设置附件上传（子）目录
//        $upload->thumbPrefix = 'th_';
//        $upload->thumbMaxWidth = '400';
//        $upload->thumbMaxHeight = '400';

        $info = $upload->upload();
        $values = array_values($info);
        $info_count = count($values);

        $cj_pics = "";
        for ($index = 0; $index < $info_count; $index++) {
            $img_path = $values[$index]["savepath"] . $values[$index]["savename"];
            /* 每张图片用;分割 */
            $cj_pics = $cj_pics . $img_path;
            if ($index < $info_count - 1) {
                $cj_pics = $cj_pics . ";";
            }
        }

        $data["cj_uid"] = $uid;
        $data["cj_cap"] = $cap;
        $data["cj_oil"] = $oil_num;
        $data["pics_count"] = $info_count;
        $data["cj_pics"] = $cj_pics;
        $data["aims_sfzh"] = $aims_sfzh;
        $data["aims_name"] = $aims_name;
        $data["aims_addr"] = $aims_addr;
        $data["phone_number"] = $phone_number;
        $data["create_at"] = $current_at;

        $result = D('oil_cj')->add($data);

        if ($result) {
            $this->apiReturn(200, '采集信息提交成功', null, ApiReturn);
        } else {
            $this->apiReturn(400, '采集信息提交失败', null, ApiReturn);
        }
    }

    /**
     * 查询采集记录
     */
    public function findcj()
    {
        if (IS_POST) {
            $uid = I('post.uid');
            $user_token = I('post.user_token');

            $time_start = I('post.time_start');
            $time_end = I('post.time_end');

            $currentPage = I('post.page_num');
            $page_size = I('post.page_size');

        } elseif (IS_GET) {
            $uid = I('get.uid');
            $user_token = I('get.user_token');

            $time_start = I('get.time_start');
            $time_end = I('get.time_end');

            $currentPage = I('get.page_num');
            $page_size = I('get.page_size');
        }

        if (empty($uid) || empty($user_token)) {
            $this->apiReturn(422, '请求参数有误', NULL, ApiReturn);
            return;
        }

        $condition['id'] = $uid;
        $condition['user_token'] = $user_token;
        $resultFind = D('user')->where($condition)->find();
        if (!$resultFind) {
            $this->apiReturn(401, '此账户不存在或token有误', null, ApiReturn);
            return;
        }

        $current_at = time();
        $update_at = $resultFind["update_at"];

        if ($update_at - $current_at >= UserTokenExpireTime) {
            $this->apiReturn(402, '令牌已失效', null, ApiReturn);
            return;
        }
        //对token 进行续期
        $this->checktoken($user_token,$uid);

        $time_start = strtotime($time_start);
        $time_end = strtotime($time_end);
        $currentPage = intval($currentPage);
        $page_size = intval($page_size);

        if ($time_end <= $time_start) {
            $this->apiReturn(403, '查询条件有误', null, ApiReturn);
            return;
        }

        $condition_cj['cj_uid'] = $uid;

        if ($time_start != 0 && $time_end != 0) {
            $condition_cj['create_at'] = array(array('egt', $time_start), array('elt', $time_end));
        }

        if ($currentPage < 1) {
            $currentPage = 1;
        }

        $list = D('oil_cj')->where($condition_cj)->order('create_at asc')->limit(($currentPage - 1) * $page_size, $page_size)->select();

        $count = count($list);

        $data["nums"] = $count;
        $data["cur_page"] = $currentPage;
        for ($index = 0; $index < $count; $index++) {
            $info[$index]["cj_id"] = $list[$index]["id"];
            $info[$index]["cj_cap"] = $list[$index]["cj_cap"];
            $info[$index]["cj_oil"] = $list[$index]["cj_oil"];
            $info[$index]["pics_count"] = $list[$index]["pics_count"];
            $info[$index]["pics"] = $list[$index]["cj_pics"];
            $info[$index]["pics_thumbs"] = $list[$index]["cj_pics_thumbs"];
            $info[$index]["aims_sfzh"] = $list[$index]["aims_sfzh"];
            $info[$index]["aims_name"] = $list[$index]["aims_name"];
            $info[$index]["aims_addr"] = $list[$index]["aims_addr"];
            $info[$index]["aims_phone"] = $list[$index]["phone_number"];
            $info[$index]["cj_at"] = $list[$index]["create_at"];
        }
        $data["info"] = $info;

        $this->apiReturn(200, '查询成功', $data, ApiReturn);
    }


    /**
     * 查看采集信息详情
     */
    public function getcjdetail()
    {
        if (IS_POST) {
            $uid = I('post.uid');
            $user_token = I('post.user_token');

            $cj_id = I('post.cj_id');

        } elseif (IS_GET) {
            $uid = I('get.uid');
            $user_token = I('get.user_token');

            $cj_id = I('get.cj_id');
        }

        if (empty($uid) || empty($user_token)) {
            $this->apiReturn(422, '请求参数有误', NULL, ApiReturn);
            return;
        }

        if (empty($cj_id)) {
            $this->apiReturn(421, '查询参数为空', NULL, ApiReturn);
            return;
        }

        $condition_user['id'] = $uid;
        $condition_user['user_token'] = $user_token;
        $resultFind = D('user')->where($condition_user)->find();
        if (!$resultFind) {
            $this->apiReturn(401, '此账户不存在或token有误', null, ApiReturn);
            return;
        }

        $current_at = time();
        $update_at = $resultFind["update_at"];

        if ($update_at - $current_at >= UserTokenExpireTime) {
            $this->apiReturn(402, '令牌已失效', null, ApiReturn);
            return;
        }
//对token 进行续期
        $this->checktoken($user_token,$uid);

        $condition_cj['id'] = $cj_id;
        $condition_cj['cj_uid'] = $uid;

        $info = D('oil_cj')->where($condition_cj)->find();
        if ($info) {
            $user = D('user')->where("id=" . $info["cj_uid"])->find();
            if ($user != null) {
                $data["cj_id"] = $info["id"];
                $data["cj_user"] = $user["user_name"];
            } else {
                $this->apiReturn(404, '记录异常', null, ApiReturn);
                return;
            }
            $data["cj_cap"] = $info["cj_cap"];
            $data["cj_oil"] = $info["cj_oil"];
            $data["pics_count"] = $info["pics_count"];
            $data["pics"] = $info["cj_pics"];
            $data["aims_sfzh"] = $info["aims_sfzh"];
            $data["aims_name"] = $info["aims_name"];
            $data["aims_addr"] = $info["aims_addr"];
            $data["aims_phone"] = $info["phone_number"];
            $data["cj_at"] = $info["create_at"];

            $this->apiReturn(200, '查询成功', $data, ApiReturn);
        } else {
            $this->apiReturn(403, '不存在此记录', null, ApiReturn);
        }
    }
    /**
     * 检测tokens是否有效
     */
    public function checkUserToken()
    {
        if (IS_POST) {
            $uid = I('post.uid');
            $user_token = I('post.user_token');

            $cj_id = I('post.cj_id');

        } elseif (IS_GET) {
            $uid = I('get.uid');
            $user_token = I('get.user_token');

            $cj_id = I('get.cj_id');
        }

        if (empty($uid) || empty($user_token)) {
            $this->apiReturn(422, '请求参数有误', NULL, ApiReturn);
            return;
        }

        if (empty($cj_id)) {
            $this->apiReturn(421, '查询参数为空', NULL, ApiReturn);
            return;
        }

        $condition_user['id'] = $uid;
        $condition_user['user_token'] = $user_token;
        $resultFind = D('user')->where($condition_user)->find();
        if (!$resultFind) {
            $this->apiReturn(401, '此账户不存在或token有误', null, ApiReturn);
            return;
        }

        $current_at = time();
        $update_at = $resultFind["update_at"];

        if ($update_at - $current_at >= UserTokenExpireTime) {
            $this->apiReturn(402, '令牌已失效', null, ApiReturn);
            return;
        }
//对token 进行续期
        $this->checktoken($user_token,$uid);

        $condition_cj['id'] = $cj_id;
        $condition_cj['cj_uid'] = $uid;

        $info = D('oil_cj')->where($condition_cj)->find();
        if ($info) {
            $user = D('user')->where("id=" . $info["cj_uid"])->find();
            if ($user != null) {
                $data["cj_id"] = $info["id"];
                $data["cj_user"] = $user["user_name"];
            } else {
                $this->apiReturn(404, '记录异常', null, ApiReturn);
                return;
            }
            $data["cj_cap"] = $info["cj_cap"];
            $data["cj_oil"] = $info["cj_oil"];
            $data["pics_count"] = $info["pics_count"];
            $data["pics"] = $info["cj_pics"];
            $data["aims_sfzh"] = $info["aims_sfzh"];
            $data["aims_name"] = $info["aims_name"];
            $data["aims_addr"] = $info["aims_addr"];
            $data["aims_phone"] = $info["phone_number"];
            $data["cj_at"] = $info["create_at"];

            $this->apiReturn(200, '查询成功', $data, ApiReturn);
        } else {
            $this->apiReturn(403, '不存在此记录', null, ApiReturn);
        }
    }

    /**
     * 检测升级
     */
    public function checkupdate()
    {

        if (IS_POST) {
            $uid = I('post.uid');
            $user_token = I('post.user_token');
            $spVersion = I('post.version');
            $spPkg = I('post.pkg');
        } elseif (IS_GET) {
            $uid = I('get.uid');
            $user_token = I('get.user_token');
            $spVersion = I('get.version');
            $spPkg = I('get.pkg');
        }

        if (empty($uid) || empty($user_token) || empty($spVersion) || empty($spPkg)) {
            $this->apiReturn(422, '请求参数有误', NULL, ApiReturn);
            return;
        }

        $condition_user['id'] = $uid;
        $condition_user['user_token'] = $user_token;
        $resultFind = D('user')->where($condition_user)->find();
        if (!$resultFind) {
            $this->apiReturn(401, '此账户不存在或token有误', null, ApiReturn);
            return;
        }

        $current_at = time();
        $update_at = $resultFind["update_at"];



        $url = "./Uploads/apk/update-metadata.xml";
        $xml = simplexml_load_file($url);
        if ($xml == null) {
            $this->apiReturn(500, '服务器错误', null, ApiReturn);
            return;
        }

        $data = null;
        $hasUpdate = false;
        foreach ($xml->children() as $child) {
            if ("versioncode" == $child->getName()) {
                $versioncode = intval("" . $child);
                $data["versioncode"] = $versioncode;
                if ($versioncode > $spVersion) {
                    $hasUpdate = true;
                }
                continue;
            } elseif ("pkg" == $child->getName()) {
                $data["pkg"] = "" . $child;
                continue;
            } elseif ("appname" == $child->getName()) {
                $data["appname"] = "" . $child;
                continue;
            } elseif ("versionname" == $child->getName()) {
                $data["versionname"] = "" . $child;
                continue;
            } elseif ("apkpath" == $child->getName()) {
                $data["fileurl"] = "" . $child;
                continue;
            } elseif ("desc" == $child->getName()) {
                $data["desc"] = "" . $child;
                continue;
            }
        }
        if ($hasUpdate) {
            if ($data["pkg"] == $spPkg) {
                $this->apiReturn(200, '检测到新版本', $data, ApiReturn);
                return;
            }
        }

        $this->apiReturn(403, '不存在新版本', null, ApiReturn);
    }

    public function test()
    {
        $string = "11.22#22.11";
        $result = explode("#", $string);
        $this->apiReturn(200, '分割成功', $result[1], ApiReturn);
    }

    /*************************以下为基础函数*************************************/

    /**
     * 判断设备是否存在
     * @param $deviceid
     * 设备ID
     * @return bool
     */
    private function isExist($account)
    {
        $device = D('user');
        $condition['account'] = $account;
        $resultFind = $device->where($condition)->find();
        return $resultFind != NULL;
    }


    /**
     * 作用：产生随机字符串，不长于32位
     * @param int $length
     * @return string
     */
    function createNoncestr($length = 32)
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

/**
 * 对token 信息进行处理
 * 如果token 有效就行延期，返回token 如果token无效返回-1
 *
 */
private function checktoken($tokenInfo,$uid)
{
    //1、根据token和uid获取user表中的信息
    $Dao=D("user");//对user表进行实例化
    // 构造查询条件
    $condition['id'] =$uid;
    $condition['user_token'] =$tokenInfo;
    //执行查询结果
    $attrs=$Dao->where($condition)->find();

    $update_at=$attrs['update_at'];
    $expire_time=$attrs['expire_time'];

    if(($expire_time+$update_at)>time())
    {
        //延期
        $data['update_at']=time();
        $result=$Dao->where($condition)->save($data);
        if($result){
            return $tokenInfo;
        }else{
            return "-1";
        }

    }else{
        return "-1";
    }
}
/**
* Created by PhpStorm.
* User: yancat
* Date: 2016/9/27
* Time: 19:34
*/
    /**
     *日志记录，按照"Ymd.log"生成当天日志文件
     * 日志路径为：入口文件所在目录/logs/$type/当天日期.log.php，例如 /logs/error/20120105.log.php
     * @param string $type 日志类型，对应logs目录下的子文件夹名
     * @param string $content 日志内容
     * @return bool true/false 写入成功则返回true
     */
    function writelog($type="",$content=""){
        if(UserWriteLog==0){
            return FALSE;
        }

        if(!$content || !$type){
            return FALSE;
        }
        $dir=getcwd().DIRECTORY_SEPARATOR.'Logs'.DIRECTORY_SEPARATOR.$type;
        if(!is_dir($dir)){
            if(!mkdir($dir)){
                return false;
            }
        }
        $filename=$dir.DIRECTORY_SEPARATOR.date("Ymd",time()).'.log';

        $logs=include $filename;

        $logs=date("Y-m-d H:i:s")." ".$content;

        if(!$fp=@fopen($filename,"a")){
            return false;
        }
        if(!fwrite($fp, $logs))return false;
        fwrite($fp,"\r");
        fclose($fp);
        return true;
    }

}
